<template>
  <div class="tags-content">
    <div class="item-details">
      <div class="tip">
        <span>标签</span>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="标签数量最多可添加10个"
          placement="top"
        >
          <el-icon>
            <QuestionFilled />
          </el-icon>
        </el-tooltip>
      </div>
      <div class="input_rapper">
        <el-input
          v-if="inputVisible"
          ref="inputRef"
          v-model="inputValue"
          @input="handleInput"
          @keydown.enter="addTag"
          @blur="inputVisible = false"
          placeholder="请输入标签内容，按ENTER键创建"
        ></el-input>
        <el-button
          v-else
          class="button-new-tag"
          size="small"
          @click="showInput"
        >
          + 输入标签按ENTER创建
        </el-button>
      </div>
    </div>
    <div class="tags-panel gap-2">
      <el-tag
        v-for="(tag, index) in tagsList"
        :key="index"
        @close="removeTag(index)"
        closable
        :disable-transitions="false"
        type="primary"
      >
        {{ tag }}
      </el-tag>
    </div>
  </div>
</template>

<script setup>
import { nextTick, ref } from "vue";
const inputValue = ref("");
let inputVisible = ref(false);
const tagsList = ref([]);
const inputRef = ref(null);

const handleInput = (value) => {
  inputValue.value = value.trim();
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    if (inputRef.value) {
      inputRef.value.focus();
    }
  });
};

const addTag = () => {
  if (inputValue.value) {
    tagsList.value.push(inputValue.value);
    inputVisible.value = false;
    inputValue.value = "";
  }
};

const removeTag = (removeIndex) => {
  if (removeIndex !== -1) {
    tagsList.value.splice(removeIndex, 1);
  }
};
</script>

<style lang="scss" scoped>
.item-details {
  display: flex;
  align-items: center;
  height: 42px;

  .tip {
    font-weight: 700;
    line-height: 32px;
    margin-right: 10px;

    & > span {
      margin-right: 5px;
    }
  }

  .input_rapper {
    display: flex;
    flex: 1;
    align-items: center;
    flex-wrap: wrap;
    width: 100%;
  }

  .button-new-tag {
    font-size: var(--base-font-size);
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
}

.tags-panel {
  margin-left: 58px;
}

.gap-2 > * {
  margin-right: 10px;
}
</style>
